﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jb.Common.Extensions;
using Jb.Domain;
using Jb.Web.ViewModels;
using Jb.Web.Utility;
using AutoMapper;
using System.Drawing;
using System.IO;

namespace Jb.Web.Areas.Private.Controllers
{
    [Authorize(Roles = "Company Admin,Company User,Admin")]
    public class CompanyController : BaseController
    {
		private JbEntities _Context = new JbEntities();
        
		#region Constructors
		public CompanyController()
		{
		}

		public CompanyController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View();
        }
		/// <summary>
        /// Gets a Company from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult ProfileEdit()
        {
            Company entity = _Context.GetCompanyByID(LoggedInUser.Contact.CompanyID);
            if (entity.Address.Email == AppConstants.ValueOf.UNKNOWN)
                entity.Address.Email = String.Empty;
            CompanyViewModel viewModel = Mapper.Map<Company, CompanyViewModel>(entity);             
            return View(viewModel);
        }

		/// <summary>
        /// Saves Company Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult ProfileEdit(CompanyViewModel viewModel)
        {
			if (!ModelState.IsValid)
                return View(viewModel);
            if (viewModel.ID != LoggedInUser.Contact.CompanyID)
                return RedirectToAccessDenied();

			Company entity = null;
            //if (viewModel.ID == 0)
            //{
            //    entity = new Company();
            //    _Context.AddToCompanies(entity);
            //}
            //else
            //{
                entity = _Context.GetCompanyByID(viewModel.ID);
                if (viewModel.Address.Email.IsNullOrEmpty())
                    viewModel.Address.Email = AppConstants.ValueOf.UNKNOWN;
            //}

            entity = Mapper.Map<CompanyViewModel, Company>(viewModel, entity);
            entity.Address = Mapper.Map<AddressViewModel, Address>(viewModel.Address, entity.Address);
            entity.ModifiedOn = entity.Address.ModifiedOn = DateTime.Now;
            entity.Address.ModifiedBy = LoggedInUser.ID;
            entity.Url = entity.Name.ToSeoUrl();
		
            _Context.SaveChanges();
            viewModel.ID = entity.ID;
            ViewData[AppConstants.ViewDataKeys.SAVED] = true;

            ///Rebuild the Content and Company Route Cache, and re-map them in the global routing cache            
            MvcApplication.RefreshRoutes(true);

            return View(viewModel);     
        }

        #region Employer/Company Logo Upload Section

        public ActionResult LogoList()
        {
            Jb.Domain.Company entity = _Context.Companies.Include("Address").FirstOrDefault(P => P.ID == LoggedInUser.Contact.CompanyID);
            CompanyViewModel viewModel = Mapper.Map<CompanyViewModel>(entity);
            return View(viewModel);
        }

        /// <summary>
        /// This Action Method is used to upload the Image
        /// </summary>
        /// <param name="companyLogo"></param>
        /// <param name="productID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult LogoList(HttpPostedFileBase companyLogo, int companyID)// = 0, int companyLogoID = 0)
        {
            Jb.Domain.Company company = _Context.Companies.FirstOrDefault(P => P.ID == companyID);
            CompanyViewModel companyViewModel = ViewBag.Company = Mapper.Map<Jb.Domain.Company, CompanyViewModel>(company);
            ViewBag.CompanyID = companyID;

            if (companyID != base.LoggedInUser.Contact.CompanyID)
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Invalid Request.";
            else if (companyLogo == null)
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Please select an Image for your company.";
            else if (!WebUtil.IsValidImageFile(companyLogo))
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Sorry! Your selected file is not a valid Image.";
            else
            {
                int w, h;
                String fileName = ImageManager.SaveTempJpeg(companyLogo.InputStream, ConfigReader.CompanyLogoAspectRatio, out w, out h);
                ViewBag.WidthHeight = String.Format("{0},{1}", w, h);
                ViewBag.CropBoxImageUrl = ImageManager.GetTempImageUrl(fileName);
                ViewData[AppConstants.ViewDataKeys.ORIGINAL_FILE_NAME] = companyLogo.FileName;
            }
            return View(companyViewModel);
        }

        [HttpPost]
        public ActionResult CropAndSaveImage(CompanyViewModel viewModel)
        {
            cropAndSaveImage(viewModel);
            return Json(viewModel);
        }

        /// <summary>
        /// Deletes a Job Seeker Photo from filesystem and Updates Database accordingly.
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeletePhoto(int companyID)
        {
            if (LoggedInUser.Contact.CompanyID != companyID)
                return Json(false);

            var company = _Context.Companies.FirstOrDefault(P => P.ID == companyID);
            if (company == null)
                return Json(false);
            else
            {
                ImageManager.DeleteCompanyLogo(company.LogoFile, companyID);
                company.LogoFile = null;
                _Context.SaveChanges();

                return Json(true);
            }
        }

        #endregion Employer/Company Logo Upload Section
        #endregion Action Methods

        #region Helper Methods

        /// <summary>
        /// Crops an image selected by a rectangle and saves it in the filesystem.
        /// </summary>
        /// <param name="viewModel"></param>
        private void cropAndSaveImage(CompanyViewModel viewModel)
        {
            if (base.LoggedInUser.Contact.CompanyID == viewModel.ID)
            {
                Jb.Domain.Company company = _Context.Companies.FirstOrDefault(P => P.ID == viewModel.ID);
                if (company != null && !viewModel.LogoFile.IsNullOrEmpty())
                {
                    String sourceImage = Server.MapPath(viewModel.LogoFile);
                    if (System.IO.File.Exists(sourceImage))
                    {
                        //Delete Existing Photo from file System, if any
                        if (!company.LogoFile.IsNullOrEmpty())
                        {
                            String existingLogo = Server.MapPath(ImageManager.GetCompanyLogoUrl(company.LogoFile, company.ID));
                            if (System.IO.File.Exists(existingLogo))
                                System.IO.File.Delete(existingLogo);
                        }
                        ///Create the Crop area with user selected rectangle
                        String[] coords = viewModel.CropProperty.Split(',');
                        viewModel.Width = (int)coords[2].ToFloat();
                        viewModel.Height = (int)coords[3].ToFloat();
                        Rectangle rectangle = new Rectangle(coords[0].ToInt(), coords[1].ToInt(), viewModel.Width, viewModel.Height);

                        String proposedFileName = Server.MapPath(ImageManager.GetCompanyLogoUrl(viewModel.OriginalFileName, viewModel.ID));
                        proposedFileName = ImageManager.GetNextFileName(proposedFileName);
                        String[] fileNames = ImageManager.SaveThumbnail(sourceImage, proposedFileName, rectangle, company.ID, true, ImageFor.CompanyLogo);

                        ///Delete Original Source Image from the Logo Directory
                        ///Also we can keep this file for future edit but keeping the source will get unnecessary space in the
                        ///serve, if user doesn't really using it. If need to change then they have to upload a new Image.                        
                        if (System.IO.File.Exists(fileNames[0]))
                            System.IO.File.Delete(fileNames[0]);

                        ///Rename the file
                        if (System.IO.File.Exists(fileNames[1]))
                        {
                            String newFileName = Path.GetFileName(fileNames[1]).Replace("_Thumb", String.Empty);
                            System.IO.File.Move(fileNames[1], Path.Combine(Path.GetDirectoryName(fileNames[1]), newFileName));
                            company.LogoFile = newFileName;
                        }

                        viewModel.LogoFile = ImageManager.GetCompanyLogoUrl(company.LogoFile, company.ID);                        

                        _Context.SaveChanges();
                    }
                }
            }
        }

        #endregion
    }
}


